package com.lizardmind.haofudoctor

import android.app.ActivityManager
import android.content.Context
import android.net.Uri
import android.support.multidex.MultiDex
import com.linxiao.framework.BaseApplication
import com.linxiao.framework.crash.CrashLog
import com.linxiao.framework.util.ke
import com.lizardmind.haofudoctor.manager.ImgManager
import com.lizardmind.haofudoctor.manager.postApi
import com.lizardmind.haofudoctor.other.DoctorInfo
import com.lizardmind.haofudoctor.other.Request
import com.lizardmind.haofudoctor.other.RongCloudUserBean
import com.lizardmind.haofudoctor.other.RongConnectEvent
import com.lizardmind.haofudoctor.other.rongYun.*
import com.squareup.leakcanary.LeakCanary
import io.reactivex.functions.Consumer
import io.rong.imkit.DefaultExtensionModule
import io.rong.imkit.RongExtensionManager
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.UserInfo
import org.greenrobot.eventbus.EventBus
import uk.co.chrisjenx.calligraphy.CalligraphyConfig

/**
 *
 * Created by Extends on 2017/10/13 11:18
 */
class AppApplication: BaseApplication() {
    override fun onCreate() {
        super.onCreate()
        //内存泄露检查
        if (LeakCanary.isInAnalyzerProcess(this)){
            return
        }
        LeakCanary.install(this)
        //开启日志邮件上传
        CrashLog.Instance.init(getAppContext(),
                "1043274460@qq.com","gkfbkpfltrnlbfeh",
                getString(R.string.app_name),
                "2563892038@qq.com","826011795@qq.com")

        //改变默认字体
        CalligraphyConfig.initDefault(CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/PingFangRegular.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build())


        RongIM.init(this)
        RongIM.registerMessageType(HaofuMessage::class.java)
        RongIM.registerMessageType(FanganTipsMessage::class.java)
        RongIM.registerMessageType(PatientsEducationMessage::class.java)
        RongIM.registerMessageTemplate(HaofuMessageItemProvider())
        RongIM.registerMessageTemplate(FanganTipsMessageItemProvider())
        RongIM.registerMessageTemplate(PatientsEducationItemProvider())
        setExtensionModule()

        RongIM.setOnReceiveMessageListener { message, i ->
            when(message.conversationType){
                Conversation.ConversationType.PRIVATE->{
                    message.targetId
                }
                Conversation.ConversationType.NONE -> {}
                Conversation.ConversationType.DISCUSSION -> {}
                Conversation.ConversationType.GROUP -> {}
                Conversation.ConversationType.CHATROOM -> {}
                Conversation.ConversationType.CUSTOMER_SERVICE -> {}
                Conversation.ConversationType.SYSTEM -> {}
                Conversation.ConversationType.APP_PUBLIC_SERVICE -> {}
                Conversation.ConversationType.PUBLIC_SERVICE -> {}
                Conversation.ConversationType.PUSH_SERVICE -> {}
                else->{}
            }
            return@setOnReceiveMessageListener false
        }
        RongIM.getInstance().setMessageAttachedUserInfo(true)
//        //刷新头像
//        RongIM.setUserInfoProvider({rId->
//            ke(rId)
//            if(rId==DOCTOR_PREFIX+DoctorInfo.id){//如果是自己
//                return@setUserInfoProvider  UserInfo(DOCTOR_PREFIX+DoctorInfo.id,DoctorInfo.name, Uri.parse(ImgManager.IMGURL+DoctorInfo.head_img))
//            }
//            postApi<Request<RongCloudUserBean>>(hashMapOf("action" to "get_type",
//                    "token" to DoctorInfo.token,
//                    "id" to rId.substring(1),
//                    "type" to rId[0].toString()),
//                    Consumer {
//                        it.dispose {
//                            val imgUrl = if(it.head_img.startsWith("http")){
//                                it.head_img
//                            }else{
//                                ImgManager.IMGURL+it.head_img
//                            }
//                            RongIM.getInstance().refreshUserInfoCache(UserInfo(rId,it.name, Uri.parse(imgUrl)))
//                        }
//                    })
//            return@setUserInfoProvider  UserInfo(DOCTOR_PREFIX+DoctorInfo.id,DoctorInfo.name, Uri.parse(ImgManager.IMGURL+DoctorInfo.head_img))
//        },true)
    }

    /**
     * 注册自定义的ExtensionModule
     */
    private fun setExtensionModule(){
        val moduleList = RongExtensionManager.getInstance().extensionModules
        if(moduleList!=null){
            val defaultModule = moduleList.firstOrNull { it is DefaultExtensionModule }
            if(defaultModule!=null){
                RongExtensionManager.getInstance().apply {
                    unregisterExtensionModule(defaultModule)
                    registerExtensionModule(AppExtensionModule())
                }
            }
        }
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    companion object {
        fun getCurProcessName(context: Context):String{
            val pid = android.os.Process.myPid()
            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            am.runningAppProcesses.forEach {
                if(it.pid == pid){
                    return it.processName
                }
            }
            return ""
        }
        fun connect(token:String){
            if(getAppContext().applicationInfo.packageName == getCurProcessName(getAppContext().applicationContext)){
                RongIM.connect(token, object : RongIMClient.ConnectCallback() {

                    /**
                     * 连接融云成功
                     * @param p0 当前 token 对应的用户 id
                     */
                    override fun onSuccess(p0: String?) {
                        ke("连接融云成功，userId："+p0)
                        EventBus.getDefault().post(RongConnectEvent(true))
                        RongIM.getInstance().setCurrentUserInfo(UserInfo(DOCTOR_PREFIX+DoctorInfo.id,DoctorInfo.name,
                                Uri.parse(if(DoctorInfo.head_img.startsWith("http")) DoctorInfo.head_img else {ImgManager.IMGURL+DoctorInfo.head_img})))
                    }
                    /**
                     * 连接融云失败
                     * @param errorCode 错误码，可到官网 查看错误码对应的注释
                     */
                    override fun onError(errorCode: RongIMClient.ErrorCode) {
                        ke("连接融云失败，错误码："+errorCode)
                        EventBus.getDefault().post(RongConnectEvent(false))
                    }

                    /**
                     * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 App Server 重新请求一个新的 Token
                     *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
                     */
                    override fun onTokenIncorrect() {
                        ke("融云Token错误")
                        EventBus.getDefault().post(RongConnectEvent(false))
                    }

                })
            }

        }


    }
}